//
//  MyOfSetViewController.m
//  PetAPP
//
//  Created by apple on 16/2/25.
//  Copyright © 2016年 Yuming. All rights reserved.
//

#import "MyOfSetViewController.h"
#import "CellOfMySetForLogin.h"
#import <YYWebImage.h>
#import "CellOfMySetForSet.h"
#import <DKNightVersion.h>
#import "DataBaseHandle.h"
#import "CellOfLeave.h"


@interface MyOfSetViewController () <UITableViewDataSource, UITableViewDelegate, CellOfLeaveDelegate>

@property (nonatomic, retain) UITableView *tableView;

@property (nonatomic, retain) NSArray *nameArr;

@property (nonatomic, retain) UISwitch *switchOfNight;

@property (nonatomic, retain) UILabel *labelOfCache;

@end

@implementation MyOfSetViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:@"AlertNoneForSet"];
    [_nameArr release];
    [_switchOfNight release];
    [_labelOfCache release];
    [_tableView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor grayColor]);
    
    [self createHeaderView];
    [self createSubView];
    self.nameArr = @[@[@"产品反馈", @"修改密码", @"收货地址管理", @"给我打个分吧", @"缓存清理" ,@"夜间模式"],@[@"消息推送设置", @"关于乐宠"]];
    [[NSNotificationCenter defaultCenter] addObserverForName:@"AlertNoneForSet" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"亲，没有该功能哦！" preferredStyle:UIAlertControllerStyleAlert];
        
        // 添加action
        UIAlertAction *actionOK = [UIAlertAction actionWithTitle:@"确定" style:0 handler:^(UIAlertAction * _Nonnull action) {
        }];
        
        [alert addAction:actionOK];
        [self presentViewController:alert animated:YES completion:nil];
    }];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 1){
        [[NSNotificationCenter defaultCenter] postNotificationName:@"AlertNoneForSet" object:nil];
    }else if(indexPath.section == 2) {

    }else if (indexPath.row == 4) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否清除缓存" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *actionOK = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            YYImageCache *cache = [YYWebImageManager sharedManager].cache;
            [cache.memoryCache removeAllObjects];
            [cache.diskCache removeAllObjects];
            
            //创建对象
            NSFileManager *manage = [NSFileManager defaultManager];
            
            //设置文件夹路径
            NSString *dir = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"Cache"];
            // 删除文件夹(目录)
            [manage removeItemAtPath:dir error:nil];
            //创建目录
            [manage createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
            
            //删除历史搜索
            [[DataBaseHandle shareDataBaseHandle] updateSQL:@"DROP TABLE history"];
            //创建SQL语句.
            NSString *createTableSQL = @"CREATE TABLE IF NOT EXISTS history(number INTEGER PRIMARY KEY AUTOINCREMENT, content text)";
            [[DataBaseHandle shareDataBaseHandle] updateSQL:createTableSQL];
            self.labelOfCache.text = @"0 K";
            
        }];
        
        UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:actionCancel];
        [alert addAction:actionOK];
        
        //  模态推出.
        [self presentViewController:alert animated:YES completion:^{}];
        
    }else if (indexPath.row == 5){
    
    }else {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"AlertNoneForSet" object:nil];
    }

}


#pragma mark - 设置每个分区cell的样式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case 2:{
            CellOfLeave *cell = [tableView dequeueReusableCellWithIdentifier:@"poolOfLeave"];
            cell.delegate = self;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
        }
        default:{
            CellOfMySetForSet *cell = [tableView dequeueReusableCellWithIdentifier:@"poolOfSet"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.labelOfTitle.text = self.nameArr[indexPath.section][indexPath.row];
            
            cell.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:0.4169 green:0.4169 blue:0.4169 alpha:1.0]);
            
            if (indexPath.row != 5) {

                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  
            }
            if (indexPath.row == 4) {
                self.labelOfCache = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 125, 10, 90, 30)];
                [cell.contentView addSubview:_labelOfCache];
                [_labelOfCache release];
                self.labelOfCache.textAlignment = NSTextAlignmentRight;
                YYImageCache *cache = [YYWebImageManager sharedManager].cache;
                if (cache.diskCache.totalCount < 1024) {
                    self.labelOfCache.text = [NSString stringWithFormat:@"%ld K", cache.diskCache.totalCount];
                }else{
                    self.labelOfCache.text = [NSString stringWithFormat:@"%.2f M", cache.diskCache.totalCount / 1024.f];
                }
                /**
                 // 获取缓存大小
                 cache.memoryCache.totalCost;
                 cache.memoryCache.totalCount;
                 cache.diskCache.totalCost;
                 cache.diskCache.totalCount;
                 
                 // 清空缓存
                 [cache.memoryCache removeAllObjects];
                 [cache.diskCache removeAllObjects];
                 
                 // 清空磁盘缓存，带进度回调
                 [cache.diskCache removeAllObjectsWithProgressBlock:^(int removedCount, int totalCount) {
                 // progress
                 } endBlock:^(BOOL error) {
                 // end
                 }];
                 */
                
                
            }
            if (indexPath.row == 5) {
                self.switchOfNight = [[UISwitch alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 70, 10, 0, 0)];
                [cell.contentView addSubview:_switchOfNight];
                [_switchOfNight release];
                
                [self.switchOfNight addTarget:self action:@selector(handleSwitch:) forControlEvents:UIControlEventValueChanged];
                if ([[NSUserDefaults standardUserDefaults] boolForKey:@"ISNIGHT"]) {
                    self.switchOfNight.on = YES;
                }else {
                    self.switchOfNight.on = NO;
                    
                }
                
            }

            return cell;            
        }
    }
}

- (void)handleLeaveLogin {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"亲，确定要退出吗!" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *actionOK = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"loginState"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"handleData" object:nil userInfo:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:actionOK];
    [alert addAction:actionCancel];
    //  模态推出.
    [self presentViewController:alert animated:YES completion:^{}];

}

- (void)handleSwitch:(UISwitch *)SWIT {
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    if ([DKNightVersionManager currentThemeVersion] == DKThemeVersionNight) {
        [DKNightVersionManager dawnComing];
    } else {
        [DKNightVersionManager nightFalling];
    }
    // 保存状态 , 程序再次启动时的偏好设置
    [user setBool:SWIT.on forKey:@"ISNIGHT"];
    [user synchronize];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SwitchChange" object:nil userInfo:@{@"switch" : @(SWIT.on)}];
    

}

#pragma mark - 设置每个cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
            return 50;
            break;
        case 1:
            return 50;
            break;
        default:
            return 100;
            break;
    }
    
    
}

#pragma mark - 设置分区间隔图层
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 10)];
    view.dk_backgroundColorPicker = DKColorWithColors([UIColor colorWithRed:0.9625 green:0.9625 blue:0.9625 alpha:1.0], [UIColor colorWithRed:0.2952 green:0.2952 blue:0.2952 alpha:1.0]);
    

    return view;
    
}


#pragma mark - 设置分区间距
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

#pragma mark - 设置每个分区的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 6;
            break;
        case 12:
            return 2;
            break;
        default:
            return 1;
            break;
    }
}


#pragma mark - 设置分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

#pragma mark - 创建tableView
- (void)createSubView {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    [_tableView release];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    
    [self.tableView registerClass:[CellOfMySetForLogin class] forCellReuseIdentifier:@"poolOfLogin"];
    
    [self.tableView registerClass:[CellOfMySetForSet class] forCellReuseIdentifier:@"poolOfSet"];
    
    [self.tableView registerClass:[CellOfLeave class] forCellReuseIdentifier:@"poolOfLeave"];
    self.tableView.dk_backgroundColorPicker = DKColorWithColors([UIColor colorWithRed:0.9625 green:0.9625 blue:0.9625 alpha:1.0], [UIColor colorWithRed:0.2952 green:0.2952 blue:0.2952 alpha:1.0]);
    

}
#pragma mark - 设置标题样式
- (void)createHeaderView {

    self.view.backgroundColor = [UIColor colorWithRed:0.9625 green:0.9625 blue:0.9625 alpha:1.0];


    UILabel *labelOfTitle = [[UILabel alloc] init];
    labelOfTitle.frame = CGRectMake(0, 0, 150, 40);
    labelOfTitle.textAlignment = NSTextAlignmentCenter;
    labelOfTitle.text = @"设置";
    labelOfTitle.font = [UIFont systemFontOfSize:20];
    self.navigationItem.titleView = labelOfTitle;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
